package ivalidator

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
	chTranslations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
)

const tagField string = "field"

func Translations(local string) (t ut.Translator, e error) {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterTagNameFunc(func(field reflect.StructField) string {
			return field.Tag.Get(tagField)
		})

		zht := zh.New()
		ent := en.New()
		uni := ut.New(ent, zht, ent)

		trans, ok := uni.GetTranslator(local)
		if !ok {
			e = fmt.Errorf("uni.GetTranslator(%s) failed", local)
			return
		}

		//register translate
		// 注册翻译器
		switch local {
		case "en":
			e = enTranslations.RegisterDefaultTranslations(v, trans)
		case "zh":
			e = chTranslations.RegisterDefaultTranslations(v, trans)
		default:
			e = enTranslations.RegisterDefaultTranslations(v, trans)
		}
		t = trans
	}
	return
}

func Translate(errs validator.ValidationErrors, trans ut.Translator) (r string) {
	for _, err := range errs {

		//翻译
		r = err.Translate(trans)
		break
	}
	return
}
